package com.whz.variablitity;

import com.google.common.base.Objects;

/**
 * @ClassName Complex 复数
 * @Description TODO 类的可变性 算术创建并返回新的Complex实例
 * @Author hong-zhi
 * @Date 2021/5/4 21:16
 * @Version 1.0
 */
public final class Complex {
    private final double re;
    private final double im;
    private int hashCode;

    public Complex(double re, double im) {
        this.re = re;
        this.im = im;
    }

    /*
    * 实数部分
    * */
    public double realPart() {
        return re;
    }
    /*
    * 虚数部分
    * */
    public double imaginaryPart() {
        return im;
    }
    /*
    * 加法
    * */
    public Complex plus(Complex c) {
        return new Complex(re + c.re, im + c.im);
    }
    /*
    * 减法
    * */
    public Complex minus(Complex c) {
        return new Complex(re - c.re, im - c.im);
    }
    /*
    * 乘法
    * */
    public Complex times(Complex c) {
        return new Complex(re * c.re - im * c.im,
                            re * c.im + im * c.re);
    }
    /*
    * 除法
    * */
    public Complex dividedBy(Complex c) {
        double temp = c.re * c.re + c.im * c.im;
        return new Complex((re * c.re + im * c.im) / temp,
                            (im * c.re - re * c.im) / temp);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Complex)) return false;
        Complex complex = (Complex) o;
        return Double.compare(complex.re, re) == 0
                && Double.compare(complex.im, im) == 0;
    }

    @Override
    public int hashCode() {
        if(hashCode != 0) {
            return hashCode;
        }
        int result = 0;
        result = Objects.hashCode(re);
        result = 31 * result + Objects.hashCode(im);
        hashCode = result;
        return hashCode;
    }

    @Override
    public String toString() {
        return '(' + re + " + " + im + "i)";
    }
}
